package com.hhh.demo.sx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhh.demo.sx.bean.Product;
import com.hhh.demo.sx.bean.Shop;
import com.hhh.demo.sx.bean.Store;
import com.hhh.demo.sx.bean.User;
import com.hhh.demo.sx.mapper.ShopMapper;
import com.hhh.demo.sx.mapper.StoreMapper;
import com.hhh.demo.sx.service.StoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.demo.sx.util.ResultMap;
import com.hhh.demo.sx.util.ResultPage;
import com.hhh.demo.sx.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hhh
 * @since 2022-01-04
 */
@Service
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ShopMapper shopMapper;



    @Override
    public Map<String, Object> findAll(int p, int limit, String condition) {
        User user = SessionUtil.getCurrentUser();
        String username=user.getUsername();
        QueryWrapper<Shop> w=new QueryWrapper<>();
        w.eq("createby",username);
        List<Shop> s= shopMapper.selectList(w);


        IPage<Store> page = null;
        QueryWrapper<Store> warpper = new QueryWrapper<>();
        Page<Store> pages = new Page<>(p, limit);
        for (int i=0;i<s.size()-1;i++){
            warpper.eq("shop_id",s.get(i).getId())
                    .or();
        }
        warpper.eq("shop_id",s.get(s.size()-1).getId());
        JSONObject jsonObject = JSONObject.parseObject(condition);
        if (jsonObject != null) {
            String name = (String) jsonObject.get("name");
            warpper.like(!username.equals(""), "name", name);
            page= storeMapper.selectPage(pages,warpper);
        } else {
            page= storeMapper.selectPage(pages,warpper);
        }
        return ResultPage.Page(page.getRecords(), page.getTotal());
    }

    @Override
    public ResultMap findByUser() {
        User user = SessionUtil.getCurrentUser();
        String username=user.getUsername();
        QueryWrapper<Shop> w=new QueryWrapper<>();
        w.eq("createby",username);
        List<Shop> s= shopMapper.selectList(w);



        QueryWrapper<Store> warpper = new QueryWrapper<>();

        for (int i=0;i<s.size()-1;i++){
            warpper.eq("shop_id",s.get(i).getId())
                    .or();
        }
        warpper.eq("shop_id",s.get(s.size()-1).getId());


        return ResultMap.success(storeMapper.selectList(warpper));
    }


}
